import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "cn.enilu.guns.bean.entity.door;"    // 此处指定包路径，也就对应实体类中的package com.topex.admin.entity;
typeMapping = [    // 此处指定对应的类型映射，如下：数据库中bigint对应生成java的Long，int|tinyint生成Integer...
                   (~/(?i)bigint/)                      : "Long",
                   (~/(?i)int|tinyint/)                 : "Integer",
                   (~/(?i)float|double|decimal|real/): "java.math.BigDecimal",
                   (~/(?i)date|datetime|timestamp/)       : "java.util.Date",
                   (~/(?i)time/)                     : "java.sql.Time",
                   (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaClassName(table.getName(), true)
  def fields = calcFields(table)
  new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + ".java")), "utf-8")).withPrintWriter { out -> generate(out, className, fields,table) }
}

def generate(out, className, fields,table) {   // 从这里开始，拼实体类的具体逻辑代码
  def tableComment = table.getComment();
  out.println "package $packageName"
  out.println ""
  out.println ""
  out.println "import lombok.Data;"     // 因为我使用了lombok插件，使用到了Data注解，所以在引包时加了这一行
  out.println "import cn.enilu.guns.bean.entity.BaseEntity;"
  out.println "import org.hibernate.annotations.Table;"

  out.println "import javax.persistence.Column;"
  out.println "import javax.persistence.Entity;"
  out.println "import org.springframework.data.jpa.domain.support.AuditingEntityListener;"
  out.println ""
  out.println "@Entity(name=\"" + table.getName() + "\")"
  out.println "@Table(appliesTo = \"" + table.getName() + "\",comment = \"${tableComment}\")"
  out.println "@Data"
  out.println "@EntityListeners(AuditingEntityListener.class)"
  out.println "public class $className extends BaseEntity {"
  out.println ""
  int i = 0
  fields.each() {   // 遍历字段，按下面的规则生成
    // 输出注释，这里唯一的是id特殊判断了一下，如果判断it.name == id, 则多添加一行@Id
    if (it.name == "id" || it.name == "createBy" || it.name == "createTime"|| it.name == "modifyBy"|| it.name == "modifyTime") {
      return
    }
    if (isNotEmpty(it.commoent)) {
      out.println "\t/**"
      out.println "\t * ${it.commoent}"
      out.println "\t */"
      out.println "\t@Column(columnDefinition = \" ${it.spec.toUpperCase()} COMMENT '${it.commoent}'\")"
    }else{
      out.println "\t/**"
      out.println "\t * "
      out.println "\t */"
      out.println "\t@Column(columnDefinition = \" ${it.spec.toUpperCase()} COMMENT ''\")"
    }
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "\tprivate ${it.type} ${it.name};"
    out.println ""
    i++
  }
  out.println ""
  out.println "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                       name : javaName(col.getName(), false),
                       type : typeStr,
                       commoent: col.getComment(),
                       annos: "",
                       spec: spec]]
  }
}

// 处理类名（这里是因为我的表都是以t_命名的，所以需要处理去掉生成类名时的开头的T，
// 如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可）
def javaClassName(str, capitalize) {
  def s = str.split(/[^\p{Alnum}]/).collect { def s = Case.LOWER.apply(it).capitalize() }.join("")
  // 去除开头的T  http://developer.51cto.com/art/200906/129168.htm
  s = s[1..s.size() - 1]
  capitalize ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
def isNotEmpty(content) {
  return content != null && content.toString().trim().length() > 0
}

def javaName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
          .collect { Case.LOWER.apply(it).capitalize() }
          .join("")
          .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}